<?php

/**
 * @Author: king
 * @Date:   2019-05-04 19:22:48
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-03 23:34:00
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;

use AstroTool\Cache\CacheManage;
use Cache;

class LanmeiUserCounselorStatus extends Base
{
    const USER_COUNSELOR_LEVEL_STATUS = ':counselor:status:level';//用户 测评 + 咨询师身份 + 等级信息 + 状态
    protected $dateFormat = 'u';
    public $guarded       = [];
    const CREATED_AT      = 'create_time';
    const UPDATED_AT      = 'update_time';
    public $timestamps    = true;
    const TAG = 'counselor_exercise';
    const CACHE_TIME = 86400 * 7;
    protected $table = 'user_counselor_status';
    /**
     * 数据库查询 用户测评认证信息
     * @param $uid
     * @return array
     * @throws ApiException
     */
    protected function getCounselorStatusData($uid)
    {
        try
        {
            $data = $this->where('uid', $uid)
                ->select('create_time','update_time','uid','divination_level','stargazer_level','xzdr_test','divination_test','stargazer_test','is_check','status','counselor_status','c_id')
                ->first();
            // 没有测评过的用户 然后默认初始数据  可通过缓存create_time是否大于0判断数据库中是否存在该条数据
            $userInfo = $data ? $data->toArray() : [
                'uid' => $uid,
                'create_time' => 0,
                'update_time' => 0,
                'divination_level' => 0,
                'stargazer_level' => 0,
                'xzdr_test' => 0,
                'divination_test' => 0,
                'stargazer_test' => 0,
                'is_check' => 0,
                'status' => 0,
                'counselor_status' => 1,
                'c_id' => 0
            ];
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', config('code.error'));
        }

        return $userInfo;
    }

    /**
     * 获取用户 测评 认证 咨询师身份信息 及 状态情况
     * @param $uid
     * @return array|bool|mixed|object
     * @throws \Exception
     */
    public function getUserCounselorStatus($uid)
    {
        $userInfo = CacheManage::getInstance()
            ->setCacheConfig('user_counselor_status', $uid)
            ->getDataAndSet(function () use ($uid)
            {
                return $this->getCounselorStatusData($uid);
            });

        return $userInfo;
    }

    /**
     * 更新用户的状态 及信息
     * @param $uid
     * @param array $updateInfo
     * @return bool
     * @throws ApiException
     * @throws \Exception
     */
    public function updateUserCounselorStatus($uid, array $updateInfo)
    {
        if (!$updateInfo)
        {
            return false;
        }
        // 获取缓存
        $data = $this->getUserCounselorStatus($uid);

        try
        {
            if ($data && isset($data['create_time']) && $data['create_time'] > 0)
            {
                // 没有异常则为成功  // 更新
                $this->save($updateInfo, ['uid' => $uid]);
            } else
            {
                // 写入 数据库
                $this->save($updateInfo);
            }
            // 写入缓存
            CacheManage::getInstance()
                ->setCacheConfig('user_counselor_status', $uid)
                ->setCache($updateInfo, 'details', true);
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', config('code.success'));
        }

        return true;
    }

    /**
     * 获取用户咨询师身份信息
     * @param $uid
     * @return array
     * @throws \Exception
     */
    public function getPersonalCounselorInfo($uid)
    {
        // 获取用户咨询师身份状态
        $userCouSta = $this->getUserCounselorStatus($uid);

        $userData = [
            'counselor' => (int)$userCouSta['status'],
            'is_check' => (int)$userCouSta['is_check'],
            'is_zxdr' => (int)$userCouSta['xzdr_test'],
            'counselor_info' => (object)[],
        ];

        if ($userCouSta['status'] > 0)
        {
            $updateData = isset($userCouSta['update_data']) ? json_decode($userCouSta['update_data'], true) : [['level_name' => '初级占星师', 'level' => 1, 'type' => 1]];
            $userData['counselor_info'] = [
            	'c_id' => (int)$userCouSta['c_id'],
                'divination_level' => (int)$userCouSta['divination_level'],
                'stargazer_level' => (int)$userCouSta['stargazer_level'],
                'update_data' => $updateData
            ];
        } else
        {
            if ($userCouSta['xzdr_test'] == 1 && ($userCouSta['divination_test'] || $userCouSta['stargazer_test']))
            {
                $userData['is_check'] = 1;
            }
        }

        return $userData;
    }

    /**
     * 升级消息通知成功
     * @param $uid
     * @throws \Exception
     */
    public function msgNotofySuccess($uid)
    {
        CacheManage::getInstance()->setCacheConfig('user_counselor_status', $uid)->setCache(['update_data' => '[]'], 'details', true);
    }
}